using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using JGSY.CMS.LowCode.Platform.Domain.Entities;
using JGSY.CMS.LowCode.Platform.Domain.Entities.Monitoring;
using JGSY.CMS.LowCode.Platform.Domain.Interfaces;
using JGSY.CMS.LowCode.Platform.Infrastructure.Services;
using Domain.Entities; // 添加 SecuritySetting 命名空间

namespace JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext
{
    /// <summary>
    /// 低代码平台数据库上下文
    /// 提供EF Core数据库上下文，管理所有实体的数据库操作和关系映射
    /// 2025-08-09: 完成数据库表名规范化重构，统一使用snake_case命名和long类型主键
    /// </summary>
    public class LowCodeDbContext : DbContext
    {
        private readonly ITenantContext? _tenantContext;
        private readonly IHttpContextAccessor? _httpContextAccessor;

        /// <summary>
        /// 配置实体模型关系和约束
        /// 设置复合主键、外键约束、字段类型映射和表名规范化
        /// </summary>
        /// <param name="modelBuilder">模型构建器</param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            
            // =============================================
            // 表名规范化配置 - 统一使用snake_case命名
            // =============================================
            
            // 核心用户系统
            modelBuilder.Entity<User>().ToTable("users");
            modelBuilder.Entity<Tenant>().ToTable("tenants");
            modelBuilder.Entity<Role>().ToTable("roles");
            modelBuilder.Entity<Permission>().ToTable("permissions");
            modelBuilder.Entity<UserRole>().ToTable("user_roles");
            modelBuilder.Entity<RolePermission>().ToTable("role_permissions");
            
            // 安全和审计系统
            modelBuilder.Entity<AuditLog>().ToTable("audit_logs");
            modelBuilder.Entity<ExceptionLog>().ToTable("exception_logs");
            modelBuilder.Entity<OperationLog>().ToTable("operation_logs");
            modelBuilder.Entity<SecurityLog>().ToTable("security_logs");
            modelBuilder.Entity<SecurityEvent>().ToTable("security_events");
            modelBuilder.Entity<LoginHistory>().ToTable("login_histories");
            modelBuilder.Entity<UserDevice>().ToTable("user_devices");
            modelBuilder.Entity<TwoFactor>().ToTable("two_factors");
            modelBuilder.Entity<RiskAssessment>().ToTable("risk_assessments");
            
            // 系统配置
            modelBuilder.Entity<SystemSetting>().ToTable("system_settings");
            modelBuilder.Entity<SecuritySetting>().ToTable("security_settings");
            modelBuilder.Entity<PermissionRouteMapping>().ToTable("permission_route_mappings");
            
            // 组织架构
            modelBuilder.Entity<Department>().ToTable("departments");
            modelBuilder.Entity<Team>().ToTable("teams");
            modelBuilder.Entity<TeamMember>().ToTable("team_members");
            
            // 内容管理
            modelBuilder.Entity<Article>().ToTable("articles");
            modelBuilder.Entity<Page>().ToTable("pages");
            modelBuilder.Entity<ContentModel>().ToTable("content_models");
            modelBuilder.Entity<ContentItem>().ToTable("content_items");
            modelBuilder.Entity<Category>().ToTable("categories");
            modelBuilder.Entity<Template>().ToTable("templates");
            modelBuilder.Entity<Theme>().ToTable("themes");
            modelBuilder.Entity<Navigation>().ToTable("navigations");
            modelBuilder.Entity<Language>().ToTable("languages");
            modelBuilder.Entity<Publish>().ToTable("publishes");
            
            // 产品和媒体
            modelBuilder.Entity<Product>().ToTable("products");
            modelBuilder.Entity<MediaFile>().ToTable("media_files");
            
            // 表单系统
            modelBuilder.Entity<Form>().ToTable("forms");
            modelBuilder.Entity<FormSubmission>().ToTable("form_submissions");
            modelBuilder.Entity<Field>().ToTable("cms_fields");
            
            // 工作流系统
            modelBuilder.Entity<Workflow>().ToTable("workflows");
            modelBuilder.Entity<WorkflowInstance>().ToTable("workflow_instances");
            modelBuilder.Entity<WorkflowTask>().ToTable("workflow_tasks");
            modelBuilder.Entity<WorkflowVersion>().ToTable("workflow_versions");
            
            // 监控系统 (已符合规范)
            modelBuilder.Entity<MonitorPerformanceMetric>().ToTable("monitor_performance_metrics");
            modelBuilder.Entity<MonitorErrorLog>().ToTable("monitor_error_logs");
            modelBuilder.Entity<MonitorSessionSummary>().ToTable("monitor_session_summary");
            modelBuilder.Entity<MonitorUserInteraction>().ToTable("monitor_user_interactions");

            // Phase 4 - 资源配额管理系统
            modelBuilder.Entity<TenantResourceQuota>().ToTable("tenant_resource_quotas");
            modelBuilder.Entity<TenantResourceUsageHistory>().ToTable("tenant_resource_usage_history");

            // Phase 4 - 租户监控分析系统  
            modelBuilder.Entity<TenantPerformanceMetric>().ToTable("tenant_performance_metrics");
            modelBuilder.Entity<TenantActivityStatistic>().ToTable("tenant_activity_statistics");
            modelBuilder.Entity<TenantCostAnalysis>().ToTable("tenant_cost_analysis");

            // Phase 4 - 数据管理工具系统
            modelBuilder.Entity<TenantDataBackup>().ToTable("tenant_data_backups");
            modelBuilder.Entity<TenantDataMigration>().ToTable("tenant_data_migrations");
            modelBuilder.Entity<TenantDataCleanup>().ToTable("tenant_data_cleanups");

            // Phase 5 - 通知管理系统
            modelBuilder.Entity<TenantNotificationConfig>().ToTable("tenant_notification_configs");
            modelBuilder.Entity<NotificationTemplate>().ToTable("notification_templates");
            modelBuilder.Entity<NotificationRecord>().ToTable("notification_records");
            modelBuilder.Entity<NotificationSubscription>().ToTable("notification_subscriptions");

            // =============================================
            // 复合主键配置
            // =============================================
            
            modelBuilder.Entity<UserRole>()
                .HasKey(ur => new { ur.UserId, ur.RoleId });
            
            modelBuilder.Entity<RolePermission>()
                .HasKey(rp => new { rp.RoleId, rp.PermissionId });
            
            modelBuilder.Entity<TeamMember>()
                .HasKey(tm => new { tm.TeamId, tm.UserId });

            // =============================================
            // 外键类型配置 - 统一使用long类型
            // =============================================
            
            // 用户角色关联
            modelBuilder.Entity<UserRole>()
                .Property(ur => ur.UserId).IsRequired();
            modelBuilder.Entity<UserRole>()
                .Property(ur => ur.RoleId).IsRequired();
                
            // 角色权限关联
            modelBuilder.Entity<RolePermission>()
                .Property(rp => rp.RoleId).IsRequired();
            modelBuilder.Entity<RolePermission>()
                .Property(rp => rp.PermissionId).IsRequired();
                
            // 安全相关
            modelBuilder.Entity<UserDevice>()
                .Property(ud => ud.UserId).IsRequired();
            modelBuilder.Entity<TwoFactor>()
                .Property(tf => tf.UserId).IsRequired();
            modelBuilder.Entity<SecurityEvent>()
                .Property(se => se.UserId);
            modelBuilder.Entity<RiskAssessment>()
                .Property(ra => ra.UserId).IsRequired();
            modelBuilder.Entity<LoginHistory>()
                .Property(lh => lh.UserId);
                
            // 内容管理
            modelBuilder.Entity<Publish>()
                .Property(p => p.UserId).IsRequired();
            modelBuilder.Entity<Page>()
                .Property(p => p.CreatedBy).IsRequired();
            modelBuilder.Entity<ContentModel>()
                .Property(cm => cm.AuthorId).IsRequired();

            // =============================================
            // JSON字段配置
            // =============================================
            
            modelBuilder.Entity<Product>()
                .Property(p => p.Attributes).HasColumnType("json");
            modelBuilder.Entity<Product>()
                .Property(p => p.Images).HasColumnType("json");
            modelBuilder.Entity<Product>()
                .Property(p => p.Videos).HasColumnType("json");
                
            modelBuilder.Entity<Form>()
                .Property(f => f.Fields).HasColumnType("json");
            modelBuilder.Entity<Form>()
                .Property(f => f.Rules).HasColumnType("json");
            modelBuilder.Entity<Form>()
                .Property(f => f.NotifyConfig).HasColumnType("json");
                
            modelBuilder.Entity<FormSubmission>()
                .Property(fs => fs.Data).HasColumnType("json");
                
            modelBuilder.Entity<Workflow>()
                .Property(w => w.Steps).HasColumnType("json");
            modelBuilder.Entity<Workflow>()
                .Property(w => w.Conditions).HasColumnType("json");
                
            modelBuilder.Entity<WorkflowVersion>()
                .Property(wv => wv.Steps).HasColumnType("json");
            modelBuilder.Entity<WorkflowVersion>()
                .Property(wv => wv.Conditions).HasColumnType("json");

            // =============================================
            // 并发控制配置
            // =============================================
            
            modelBuilder.Entity<Workflow>()
                .Property(w => w.RowVersion)
                .IsConcurrencyToken()
                .ValueGeneratedOnAddOrUpdate();

            // =============================================
            // 索引配置优化
            // =============================================
            
            // 用户系统核心索引
            modelBuilder.Entity<User>()
                .HasIndex(u => u.Username)
                .IsUnique()
                .HasDatabaseName("ix_users_username_unique");
            
            modelBuilder.Entity<User>()
                .HasIndex(u => u.Email)
                .IsUnique()
                .HasDatabaseName("ix_users_email_unique");
            
            modelBuilder.Entity<User>()
                .HasIndex(u => new { u.Status, u.CreatedAt })
                .HasDatabaseName("ix_users_status_created");
            
            // 审计和日志索引
            modelBuilder.Entity<AuditLog>()
                .HasIndex(a => new { a.UserId, a.Timestamp })
                .HasDatabaseName("ix_audit_logs_user_timestamp");
            
            modelBuilder.Entity<AuditLog>()
                .HasIndex(a => a.Type)
                .HasDatabaseName("ix_audit_logs_type");
            
            modelBuilder.Entity<LoginHistory>()
                .HasIndex(l => new { l.UserId, l.CreatedAt })
                .HasDatabaseName("ix_login_histories_user_created");
            
            modelBuilder.Entity<LoginHistory>()
                .HasIndex(l => l.IpAddress)
                .HasDatabaseName("ix_login_histories_ip");
            
            // 安全事件索引
            modelBuilder.Entity<SecurityEvent>()
                .HasIndex(s => new { s.EventType, s.CreatedAt })
                .HasDatabaseName("ix_security_events_type_created");
            
            modelBuilder.Entity<SecurityEvent>()
                .HasIndex(s => s.UserId)
                .HasDatabaseName("ix_security_events_user");
            
            // 权限系统索引
            modelBuilder.Entity<UserRole>()
                .HasIndex(ur => ur.UserId)
                .HasDatabaseName("ix_user_roles_user_id");
            
            modelBuilder.Entity<UserRole>()
                .HasIndex(ur => ur.RoleId)
                .HasDatabaseName("ix_user_roles_role_id");
            
            modelBuilder.Entity<RolePermission>()
                .HasIndex(rp => rp.RoleId)
                .HasDatabaseName("ix_role_permissions_role_id");
            
            modelBuilder.Entity<RolePermission>()
                .HasIndex(rp => rp.PermissionId)
                .HasDatabaseName("ix_role_permissions_permission_id");
            
            // 权限路由映射索引
            modelBuilder.Entity<PermissionRouteMapping>()
                .HasIndex(m => new { m.Path, m.Method })
                .IsUnique()
                .HasDatabaseName("ix_permission_route_mappings_path_method_unique");
            
            modelBuilder.Entity<PermissionRouteMapping>()
                .HasIndex(m => m.Priority)
                .HasDatabaseName("ix_permission_route_mappings_priority");
            
            modelBuilder.Entity<PermissionRouteMapping>()
                .HasIndex(m => m.IsActive)
                .HasDatabaseName("ix_permission_route_mappings_active");
            
            modelBuilder.Entity<PermissionRouteMapping>()
                .HasIndex(m => m.Group)
                .HasDatabaseName("ix_permission_route_mappings_group");
            
            // 内容管理索引
            modelBuilder.Entity<Article>()
                .HasIndex(a => a.Slug)
                .IsUnique()
                .HasDatabaseName("ix_articles_slug_unique");
            
            modelBuilder.Entity<Article>()
                .HasIndex(a => new { a.Status, a.PublishedAt })
                .HasDatabaseName("ix_articles_status_published");
            
            modelBuilder.Entity<Page>()
                .HasIndex(p => p.Slug)
                .IsUnique()
                .HasDatabaseName("ix_pages_slug_unique");
            
            modelBuilder.Entity<Page>()
                .HasIndex(p => new { p.Status, p.CreatedAt })
                .HasDatabaseName("ix_pages_status_created");
            
            // 分类系统索引
            modelBuilder.Entity<Category>()
                .HasIndex(c => c.Slug)
                .IsUnique()
                .HasDatabaseName("ix_categories_slug_unique");
            
            modelBuilder.Entity<Category>()
                .HasIndex(c => new { c.ParentId, c.SortOrder })
                .HasDatabaseName("ix_categories_parent_sort");
            
            // 媒体文件索引
            modelBuilder.Entity<MediaFile>()
                .HasIndex(m => m.MimeType)
                .HasDatabaseName("ix_media_files_mime_type");
            
            modelBuilder.Entity<MediaFile>()
                .HasIndex(m => new { m.CreatedBy, m.CreatedAt })
                .HasDatabaseName("ix_media_files_created_by_at");
            
            // 表单系统索引
            modelBuilder.Entity<FormSubmission>()
                .HasIndex(fs => new { fs.FormId, fs.SubmitTime })
                .HasDatabaseName("ix_form_submissions_form_submit_time");
            
            // 工作流系统索引
            modelBuilder.Entity<WorkflowInstance>()
                .HasIndex(wi => new { wi.WorkflowId, wi.Status })
                .HasDatabaseName("ix_workflow_instances_workflow_status");
            
            modelBuilder.Entity<WorkflowTask>()
                .HasIndex(wt => new { wt.AssigneeId, wt.Status })
                .HasDatabaseName("ix_workflow_tasks_assignee_status");
                
            // 工作流版本唯一索引
            modelBuilder.Entity<WorkflowVersion>()
                .HasIndex(v => new { v.WorkflowId, v.Version })
                .IsUnique()
                .HasDatabaseName("ix_workflow_versions_workflow_version_unique");
            
            // 监控系统索引优化
            modelBuilder.Entity<MonitorPerformanceMetric>(entity =>
            {
                entity.Property(e => e.MetricValue).HasPrecision(10, 2);
                entity.HasIndex(e => e.SessionId)
                    .HasDatabaseName("ix_monitor_performance_metrics_session_id");
                entity.HasIndex(e => e.MetricName)
                    .HasDatabaseName("ix_monitor_performance_metrics_metric_name");
                entity.HasIndex(e => e.Timestamp)
                    .HasDatabaseName("ix_monitor_performance_metrics_timestamp");
                entity.HasIndex(e => new { e.MetricName, e.Timestamp })
                    .HasDatabaseName("ix_monitor_performance_metrics_name_timestamp");
            });

            modelBuilder.Entity<MonitorErrorLog>(entity =>
            {
                entity.HasIndex(e => e.SessionId)
                    .HasDatabaseName("ix_monitor_error_logs_session_id");
                entity.HasIndex(e => e.ErrorType)
                    .HasDatabaseName("ix_monitor_error_logs_error_type");
                entity.HasIndex(e => e.Severity)
                    .HasDatabaseName("ix_monitor_error_logs_severity");
                entity.HasIndex(e => e.Fingerprint)
                    .HasDatabaseName("ix_monitor_error_logs_fingerprint");
                entity.HasIndex(e => e.CreatedAt)
                    .HasDatabaseName("ix_monitor_error_logs_created_at");
                entity.HasIndex(e => new { e.ErrorType, e.Timestamp })
                    .HasDatabaseName("ix_monitor_error_logs_type_timestamp");
            });

            modelBuilder.Entity<MonitorSessionSummary>(entity =>
            {
                entity.HasIndex(e => e.SessionId)
                    .IsUnique()
                    .HasDatabaseName("ix_monitor_session_summary_session_id_unique");
                entity.HasIndex(e => e.SessionStart)
                    .HasDatabaseName("ix_monitor_session_summary_session_start");
                entity.HasIndex(e => e.UserId)
                    .HasDatabaseName("ix_monitor_session_summary_user_id");
                entity.Property(e => e.AvgLCP).HasPrecision(8, 2);
                entity.Property(e => e.AvgFID).HasPrecision(8, 2);
                entity.Property(e => e.AvgCLS).HasPrecision(6, 4);
                entity.Property(e => e.AvgFCP).HasPrecision(8, 2);
                entity.Property(e => e.AvgTTFB).HasPrecision(8, 2);
            });

            modelBuilder.Entity<MonitorUserInteraction>(entity =>
            {
                entity.HasIndex(e => e.SessionId)
                    .HasDatabaseName("ix_monitor_user_interactions_session_id");
                entity.HasIndex(e => e.InteractionType)
                    .HasDatabaseName("ix_monitor_user_interactions_interaction_type");
                entity.HasIndex(e => e.Timestamp)
                    .HasDatabaseName("ix_monitor_user_interactions_timestamp");
            });
            
            // =============================================
            // 软删除全局过滤器 - 仅对支持软删除的实体配置
            // =============================================
            
            // 注意：只有实际包含IsDeleted属性的实体才配置软删除过滤器
            // 具体实体需要根据实际情况调整
            
            /*
            modelBuilder.Entity<User>()
                .HasQueryFilter(u => !u.IsDeleted);
            
            modelBuilder.Entity<Article>()
                .HasQueryFilter(a => !a.IsDeleted);
            
            modelBuilder.Entity<Page>()
                .HasQueryFilter(p => !p.IsDeleted);
            */

            // =============================================
            // 外键关系配置
            // =============================================
            
            // 配置所有租户实体与Tenant的关系 - 通过TenantId关联到Tenant.TenantId而不是Tenant.Id
            
            // Article与Tenant的关系
            modelBuilder.Entity<Article>()
                .HasOne(a => a.Tenant)
                .WithMany()
                .HasPrincipalKey(t => t.TenantId)
                .HasForeignKey(a => a.TenantId)
                .OnDelete(DeleteBehavior.Cascade);

            // Category与Tenant的关系
            modelBuilder.Entity<Category>()
                .HasOne(c => c.Tenant)
                .WithMany()
                .HasPrincipalKey(t => t.TenantId)
                .HasForeignKey(c => c.TenantId)
                .OnDelete(DeleteBehavior.Cascade);

            // Form与Tenant的关系
            modelBuilder.Entity<Form>()
                .HasOne(f => f.Tenant)
                .WithMany()
                .HasPrincipalKey(t => t.TenantId)
                .HasForeignKey(f => f.TenantId)
                .OnDelete(DeleteBehavior.Cascade);

            // Page与Tenant的关系
            modelBuilder.Entity<Page>()
                .HasOne(p => p.Tenant)
                .WithMany()
                .HasPrincipalKey(t => t.TenantId)
                .HasForeignKey(p => p.TenantId)
                .OnDelete(DeleteBehavior.Cascade);

            // Product与Tenant的关系
            modelBuilder.Entity<Product>()
                .HasOne(p => p.Tenant)
                .WithMany()
                .HasPrincipalKey(t => t.TenantId)
                .HasForeignKey(p => p.TenantId)
                .OnDelete(DeleteBehavior.Cascade);

            // Role与Tenant的关系
            modelBuilder.Entity<Role>()
                .HasOne(r => r.Tenant)
                .WithMany(t => t.Roles)
                .HasPrincipalKey(t => t.TenantId)
                .HasForeignKey(r => r.TenantId)
                .OnDelete(DeleteBehavior.Cascade);

            // Template与Tenant的关系
            modelBuilder.Entity<Template>()
                .HasOne(t => t.Tenant)
                .WithMany()
                .HasPrincipalKey(ten => ten.TenantId)
                .HasForeignKey(t => t.TenantId)
                .OnDelete(DeleteBehavior.Cascade);

            // User与Tenant的关系
            modelBuilder.Entity<User>()
                .HasOne(u => u.Tenant)
                .WithMany(t => t.Users)
                .HasPrincipalKey(t => t.TenantId)
                .HasForeignKey(u => u.TenantId)
                .OnDelete(DeleteBehavior.Cascade);

            // =============================================
            // 多租户全局查询过滤器配置
            // 为所有实现ITenantEntity接口的实体添加租户隔离过滤器
            // =============================================
            ConfigureTenantQueryFilters(modelBuilder);
        }

        /// <summary>
        /// 配置多租户全局查询过滤器
        /// 为所有实现ITenantEntity接口的实体自动添加租户隔离过滤器
        /// </summary>
        /// <param name="modelBuilder">模型构建器</param>
        private void ConfigureTenantQueryFilters(ModelBuilder modelBuilder)
        {
            // 获取当前租户ID，如果未设置则返回空字符串（不匹配任何租户）
            var currentTenantId = _tenantContext?.TenantId ?? string.Empty;

            // 为用户实体添加租户过滤器（已实现ITenantEntity）
            modelBuilder.Entity<User>()
                .HasQueryFilter(u => u.TenantId == currentTenantId);

            // 为文章实体添加租户过滤器（已实现ITenantEntity）  
            modelBuilder.Entity<Article>()
                .HasQueryFilter(a => a.TenantId == currentTenantId);

            // 为页面实体添加租户过滤器（已实现ITenantEntity）
            modelBuilder.Entity<Page>()
                .HasQueryFilter(p => p.TenantId == currentTenantId);

            // 为产品实体添加租户过滤器（已实现ITenantEntity）
            modelBuilder.Entity<Product>()
                .HasQueryFilter(p => p.TenantId == currentTenantId);

            // 为分类实体添加租户过滤器（已实现ITenantEntity）
            modelBuilder.Entity<Category>()
                .HasQueryFilter(c => c.TenantId == currentTenantId);

            // 为模板实体添加租户过滤器（已实现ITenantEntity）
            modelBuilder.Entity<Template>()
                .HasQueryFilter(t => t.TenantId == currentTenantId);

            // 为权限实体添加租户过滤器（已实现ITenantEntity）
            modelBuilder.Entity<Permission>()
                .HasQueryFilter(p => p.TenantId == currentTenantId);

            // 为部门实体添加租户过滤器（已实现ITenantEntity）
            modelBuilder.Entity<Department>()
                .HasQueryFilter(d => d.TenantId == currentTenantId);

            // 为团队实体添加租户过滤器（已实现ITenantEntity）
            modelBuilder.Entity<Team>()
                .HasQueryFilter(t => t.TenantId == currentTenantId);

            // 为团队成员实体添加租户过滤器（已实现ITenantEntity）
            modelBuilder.Entity<TeamMember>()
                .HasQueryFilter(tm => tm.TenantId == currentTenantId);

            // 为工作流实体添加租户过滤器（已实现ITenantEntity）
            modelBuilder.Entity<Workflow>()
                .HasQueryFilter(w => w.TenantId == currentTenantId);

            // 为工作流实例实体添加租户过滤器（新增ITenantEntity）
            modelBuilder.Entity<WorkflowInstance>()
                .HasQueryFilter(wi => wi.TenantId == currentTenantId);

            // 为工作流任务实体添加租户过滤器（新增ITenantEntity）
            modelBuilder.Entity<WorkflowTask>()
                .HasQueryFilter(wt => wt.TenantId == currentTenantId);

            // Phase 4 - 资源配额管理实体租户过滤器
            modelBuilder.Entity<TenantResourceQuota>()
                .HasQueryFilter(q => q.TenantId == currentTenantId);

            modelBuilder.Entity<TenantResourceUsageHistory>()
                .HasQueryFilter(h => h.TenantId == currentTenantId);

            // Phase 4 - 租户监控分析实体租户过滤器
            modelBuilder.Entity<TenantPerformanceMetric>()
                .HasQueryFilter(m => m.TenantId == currentTenantId);

            modelBuilder.Entity<TenantActivityStatistic>()
                .HasQueryFilter(s => s.TenantId == currentTenantId);

            modelBuilder.Entity<TenantCostAnalysis>()
                .HasQueryFilter(c => c.TenantId == currentTenantId);

            // Phase 4 - 数据管理工具实体租户过滤器
            modelBuilder.Entity<TenantDataBackup>()
                .HasQueryFilter(b => b.TenantId == currentTenantId);

            modelBuilder.Entity<TenantDataMigration>()
                .HasQueryFilter(m => m.TenantId == currentTenantId);

            modelBuilder.Entity<TenantDataCleanup>()
                .HasQueryFilter(c => c.TenantId == currentTenantId);

            // Phase 5 - 通知管理实体租户过滤器
            modelBuilder.Entity<TenantNotificationConfig>()
                .HasQueryFilter(c => c.TenantId == currentTenantId);

            modelBuilder.Entity<NotificationTemplate>()
                .HasQueryFilter(t => t.TenantId == currentTenantId);

            modelBuilder.Entity<NotificationRecord>()
                .HasQueryFilter(r => r.TenantId == currentTenantId);

            modelBuilder.Entity<NotificationSubscription>()
                .HasQueryFilter(s => s.TenantId == currentTenantId);

            // Phase 6 - 系统管理实体租户过滤器（2025-08-10 新增）
            modelBuilder.Entity<SystemSetting>()
                .HasQueryFilter(s => s.TenantId == currentTenantId);

            modelBuilder.Entity<SecuritySetting>()
                .HasQueryFilter(s => s.TenantId == currentTenantId);

            modelBuilder.Entity<UserDevice>()
                .HasQueryFilter(d => d.TenantId == currentTenantId);

            // Phase 7 - 监控分析实体租户过滤器（2025-08-10 新发现并实现）
            modelBuilder.Entity<MonitorErrorLog>()
                .HasQueryFilter(e => e.TenantId == currentTenantId);

            modelBuilder.Entity<MonitorPerformanceMetric>()
                .HasQueryFilter(m => m.TenantId == currentTenantId);

            modelBuilder.Entity<MonitorSessionSummary>()
                .HasQueryFilter(s => s.TenantId == currentTenantId);

            modelBuilder.Entity<MonitorUserInteraction>()
                .HasQueryFilter(i => i.TenantId == currentTenantId);

            // TODO: 待转换实体的租户过滤器（当这些实体实现ITenantEntity后启用）
            /*
            // 媒体实体（如果存在）
            modelBuilder.Entity<Media>()
                .HasQueryFilter(m => m.TenantId == currentTenantId);
            */
        }

        /// <summary>
        /// 初始化低代码平台数据库上下文实例
        /// </summary>
        /// <param name="options">数据库上下文配置选项</param>
        /// <param name="tenantContext">租户上下文服务（可选）</param>
        /// <param name="httpContextAccessor">HTTP上下文访问器（可选）</param>
        public LowCodeDbContext(DbContextOptions<LowCodeDbContext> options, 
            ITenantContext? tenantContext = null,
            IHttpContextAccessor? httpContextAccessor = null) : base(options) 
        { 
            _tenantContext = tenantContext;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 获取当前租户ID
        /// 优先从TenantContext获取，其次从HttpContext获取
        /// </summary>
        /// <returns>当前租户ID，如果未找到则返回空字符串</returns>
        private string GetCurrentTenantId()
        {
            // 优先从ITenantContext获取
            if (_tenantContext?.TenantId is not null)
            {
                return _tenantContext.TenantId;
            }

            // 其次从HttpContext获取
            if (_httpContextAccessor?.HttpContext?.Items["TenantId"] is string tenantId)
            {
                return tenantId;
            }

            // 最后检查HttpContext的其他可能位置
            var headers = _httpContextAccessor?.HttpContext?.Request?.Headers;
            if (headers?.ContainsKey("X-Tenant-Id") == true)
            {
                return headers["X-Tenant-Id"].ToString();
            }

            return string.Empty;
        }

        /// <summary>
        /// 为新增实体自动设置租户ID
        /// </summary>
        private void SetTenantIdForNewEntities()
        {
            var currentTenantId = GetCurrentTenantId();
            if (string.IsNullOrEmpty(currentTenantId)) 
                return;

            var entries = ChangeTracker.Entries<ITenantEntity>()
                .Where(e => e.State == EntityState.Added && string.IsNullOrEmpty(e.Entity.TenantId));

            foreach (var entry in entries)
            {
                entry.Entity.TenantId = currentTenantId;
            }
        }

        /// <summary>
        /// 验证租户隔离完整性
        /// 确保更新和删除操作只能在同一租户内进行
        /// </summary>
        private void ValidateTenantIsolation()
        {
            var currentTenantId = GetCurrentTenantId();
            if (string.IsNullOrEmpty(currentTenantId)) 
                return;

            var invalidEntries = ChangeTracker.Entries<ITenantEntity>()
                .Where(e => (e.State == EntityState.Modified || e.State == EntityState.Deleted) 
                           && e.Entity.TenantId != currentTenantId)
                .ToList();

            if (invalidEntries.Any())
            {
                var entityNames = string.Join(", ", invalidEntries.Select(e => e.Entity.GetType().Name));
                throw new InvalidOperationException(
                    $"租户隔离验证失败: 尝试修改或删除其他租户的数据。受影响实体: {entityNames}。" +
                    $"当前租户: {currentTenantId}");
            }
        }

        /// <summary>
        /// 重写SaveChanges方法以支持多租户自动化处理
        /// </summary>
        public override int SaveChanges()
        {
            SetTenantIdForNewEntities();
            ValidateTenantIsolation();
            return base.SaveChanges();
        }

        /// <summary>
        /// 重写SaveChangesAsync方法以支持多租户自动化处理
        /// </summary>
        public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            SetTenantIdForNewEntities();
            ValidateTenantIsolation();
            return await base.SaveChangesAsync(cancellationToken);
        }

        // Entity Sets - 实体集合属性，用于访问各个数据表

        /// <summary>
        /// 用户实体集合
        /// </summary>
        public DbSet<User> Users { get; set; }
        
        /// <summary>
        /// 租户实体集合
        /// </summary>
        public DbSet<Tenant> Tenants { get; set; }
        
        /// <summary>
        /// 页面实体集合
        /// </summary>
        public DbSet<Page> Pages { get; set; }
        
        /// <summary>
        /// 内容模型实体集合
        /// </summary>
        public DbSet<ContentModel> ContentModels { get; set; }
        
        /// <summary>
        /// 内容项实体集合
        /// </summary>
        public DbSet<ContentItem> ContentItems { get; set; }
        
        /// <summary>
        /// 发布记录实体集合
        /// </summary>
        public DbSet<Publish> Publishes { get; set; }
        
        /// <summary>
        /// 登录历史实体集合
        /// </summary>
        public DbSet<LoginHistory> LoginHistories { get; set; }
        
        /// <summary>
        /// 用户设备实体集合
        /// </summary>
        public DbSet<UserDevice> UserDevices { get; set; }
        
        /// <summary>
        /// 安全事件实体集合
        /// </summary>
        public DbSet<SecurityEvent> SecurityEvents { get; set; }
        
        /// <summary>
        /// 风险评估实体集合
        /// </summary>
        public DbSet<RiskAssessment>  RiskAssessments { get; set; } 
        
        /// <summary>
        /// 双因子认证实体集合
        /// </summary>
        public DbSet<TwoFactor> TwoFactors { get; set; }
        
        /// <summary>
        /// 角色实体集合
        /// </summary>
        public DbSet<Role> Roles { get; set; }
        
        /// <summary>
        /// 权限实体集合
        /// </summary>
        public DbSet<Permission> Permissions { get; set; }
        
        /// <summary>
        /// 用户角色关联实体集合
        /// </summary>
        public DbSet<UserRole> UserRoles { get; set; }
        
        /// <summary>
        /// 角色权限关联实体集合
        /// </summary>
        public DbSet<RolePermission> RolePermissions { get; set; }
        
        /// <summary>
        /// 系统设置实体集合
        /// </summary>
        public DbSet<SystemSetting> SystemSettings { get; set; }
        
        /// <summary>
        /// 安全设置实体集合
        /// </summary>
        public DbSet<SecuritySetting> SecuritySettings { get; set; }
        
        /// <summary>
        /// 审计日志实体集合
        /// </summary>
        public DbSet<AuditLog> AuditLogs { get; set; }
        
        /// <summary>
        /// 文章实体集合
        /// </summary>
        public DbSet<Article> Articles { get; set; }
        
        /// <summary>
        /// 产品实体集合
        /// </summary>
        public DbSet<Product> Products { get; set; }
        
        /// <summary>
        /// 媒体文件实体集合
        /// </summary>
        public DbSet<MediaFile> MediaFiles { get; set; }
        
        /// <summary>
        /// 表单定义实体集合
        /// </summary>
        public DbSet<Form> Forms { get; set; }
        
        /// <summary>
        /// 表单提交记录实体集合
        /// </summary>
        public DbSet<FormSubmission> FormSubmissions { get; set; }
        
        /// <summary>
        /// 字段定义实体集合
        /// </summary>
        public DbSet<Field> Fields { get; set; }
        
        /// <summary>
        /// 部门实体集合
        /// </summary>
        public DbSet<Department> Departments { get; set; }
        
        /// <summary>
        /// 团队实体集合
        /// </summary>
        public DbSet<Team> Teams { get; set; }
        
        /// <summary>
        /// 团队成员实体集合
        /// </summary>
        public DbSet<TeamMember> TeamMembers { get; set; }
        
        /// <summary>
        /// 工作流定义实体集合
        /// </summary>
        public DbSet<Workflow> Workflows { get; set; }
        
        /// <summary>
        /// 工作流实例实体集合
        /// </summary>
        public DbSet<WorkflowInstance> WorkflowInstances { get; set; }
        
        /// <summary>
        /// 工作流任务实体集合
        /// </summary>
        public DbSet<WorkflowTask> WorkflowTasks { get; set; }

        /// <summary>
        /// 分类管理实体集合
        /// </summary>
        public DbSet<Category> Categories { get; set; }

        /// <summary>
        /// 页面模板实体集合
        /// </summary>
        public DbSet<Template> Templates { get; set; }

        /// <summary>
        /// 导航菜单实体集合
        /// </summary>
        public DbSet<Navigation> Navigations { get; set; }

        /// <summary>
        /// 网站主题实体集合
        /// </summary>
        public DbSet<Theme> Themes { get; set; }

        /// <summary>
        /// 多语言配置实体集合
        /// </summary>
        public DbSet<Language> Languages { get; set; }

    /// <summary>
    /// 工作流版本实体集合
    /// </summary>
    public DbSet<WorkflowVersion> WorkflowVersions { get; set; }

    /// <summary>
    /// 权限路由映射实体集合
    /// </summary>
    public DbSet<PermissionRouteMapping> PermissionRouteMappings { get; set; }

    /// <summary>
    /// 异常日志实体集合
    /// </summary>
    public DbSet<ExceptionLog> ExceptionLogs { get; set; }

    /// <summary>
    /// 操作日志实体集合
    /// </summary>
    public DbSet<OperationLog> OperationLogs { get; set; }

    /// <summary>
    /// 安全日志实体集合
    /// </summary>
    public DbSet<SecurityLog> SecurityLogs { get; set; }

    // ==========================================
    // 监控系统 DbSet 集合
    // ==========================================

    /// <summary>
    /// 监控性能指标实体集合
    /// </summary>
    public DbSet<MonitorPerformanceMetric> MonitorPerformanceMetrics { get; set; }

    /// <summary>
    /// 监控错误日志实体集合
    /// </summary>
    public DbSet<MonitorErrorLog> MonitorErrorLogs { get; set; }

    /// <summary>
    /// 监控会话汇总实体集合
    /// </summary>
    public DbSet<MonitorSessionSummary> MonitorSessionSummary { get; set; }

    /// <summary>
    /// 监控用户交互实体集合
    /// </summary>
    public DbSet<MonitorUserInteraction> MonitorUserInteractions { get; set; }

    // =============================================
    // Phase 4 - 资源配额管理实体集合
    // =============================================

    /// <summary>
    /// 租户资源配额实体集合
    /// </summary>
    public DbSet<TenantResourceQuota> TenantResourceQuotas { get; set; }

    /// <summary>
    /// 租户资源使用历史实体集合
    /// </summary>
    public DbSet<TenantResourceUsageHistory> TenantResourceUsageHistories { get; set; }

    // =============================================
    // Phase 4 - 租户监控分析实体集合
    // =============================================

    /// <summary>
    /// 租户性能指标实体集合
    /// </summary>
    public DbSet<TenantPerformanceMetric> TenantPerformanceMetrics { get; set; }

    /// <summary>
    /// 租户活动统计实体集合
    /// </summary>
    public DbSet<TenantActivityStatistic> TenantActivityStatistics { get; set; }

    /// <summary>
    /// 租户成本分析实体集合
    /// </summary>
    public DbSet<TenantCostAnalysis> TenantCostAnalyses { get; set; }

    // =============================================
    // Phase 4 - 数据管理工具实体集合
    // =============================================

    /// <summary>
    /// 租户数据备份实体集合
    /// </summary>
    public DbSet<TenantDataBackup> TenantDataBackups { get; set; }

    /// <summary>
    /// 租户数据迁移实体集合
    /// </summary>
    public DbSet<TenantDataMigration> TenantDataMigrations { get; set; }

    /// <summary>
    /// 租户数据清理实体集合
    /// </summary>
    public DbSet<TenantDataCleanup> TenantDataCleanups { get; set; }

    // =============================================
    // Phase 5: 通知管理系统实体集合
    // =============================================

    /// <summary>
    /// 租户通知配置实体集合
    /// </summary>
    public DbSet<TenantNotificationConfig> TenantNotificationConfigs { get; set; }

    /// <summary>
    /// 通知模板实体集合
    /// </summary>
    public DbSet<NotificationTemplate> NotificationTemplates { get; set; }

    /// <summary>
    /// 通知记录实体集合
    /// </summary>
    public DbSet<NotificationRecord> NotificationRecords { get; set; }

    /// <summary>
    /// 通知订阅实体集合
    /// </summary>
    public DbSet<NotificationSubscription> NotificationSubscriptions { get; set; }

    // =============================================
    // Phase 6: 企业级审计日志系统实体集合
    // =============================================

    /// <summary>
    /// 审计规则实体集合
    /// </summary>
    public DbSet<AuditRule> AuditRules { get; set; }

    /// <summary>
    /// 审计报告实体集合
    /// </summary>
    public DbSet<AuditReport> AuditReports { get; set; }

    /// <summary>
    /// 审计配置实体集合
    /// </summary>
    public DbSet<AuditConfiguration> AuditConfigurations { get; set; }
    }
}